/*
PearReview - The peer review assistant.
Copyright (C) 2009  Dimitrij Pankratz, Anton Musichin
http://www.pearreview.com, info@pearreview.com

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

package com.pearreview.reviewerplugin;

import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.io.Serializable;
import java.util.List;

import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.GroupLayout;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.LayoutStyle;
import javax.swing.ListSelectionModel;
import javax.swing.SwingUtilities;

import com.pearreview.ui.list.DefaultAdvancedListCellRenderer;
import com.pearreview.util.DoubleClickMouseAdapter;
import com.pearreview.application.FileHistory;
import com.pearreview.application.Messages;
import com.pearreview.application.PluginAdapter;
import com.pearreview.application.FileHistory.ChangeEvent;

public class StartPanel extends ReviewerPanel {
	private static final long serialVersionUID = -6659036603402414978L;
	private PluginAdapter pluginAdapter;
	private ActionListener newReport;
	private ActionListener openReport;
	private ActionListener openReportFile;
	
	private JList fileList;
	private File historyFile;
	
	
	public StartPanel(PluginAdapter pluginAdapter, ActionListener newReport, 
			ActionListener openReport, ActionListener openReportFile) {
		this.newReport = newReport;
		this.openReport = openReport;
		this.openReportFile = openReportFile;
		this.pluginAdapter = pluginAdapter;
		buildList();
		
		/* file history */
		FileHistory fileHistory = pluginAdapter.getFileHistory();
		fileHistory.addChangeListener(new FileHistoryChangeListener());
		setFileHistory(fileHistory);
	}
	
	/**
	 * Returns localized string of this component
	 * @param key key of string to localize
	 * @return localized string of this component
	 */
	private static String getLocalizedString(String key) {
		return Messages.getString("PearReview.Reviewer.start." + key);
	}
	
	private void buildList() {
		setFont(new Font("Tahoma", Font.PLAIN, 12));
		
		Application[] elements = new Application[] {
			new Application(getLocalizedString("new_file"), "new.png"),
			new Application(getLocalizedString("open_file"), "open.png")
		};
		
		final JList list = new JList(elements);
		list.setCellRenderer(new ApplicationListCellRenderer());
		list.setLayoutOrientation(JList.HORIZONTAL_WRAP);
		list.setVisibleRowCount(1);
		list.setBorder(BorderFactory.createEtchedBorder());
		list.addMouseListener(new DoubleClickMouseAdapter() {
			private static final long serialVersionUID = 5371709922523055875L;
			@Override
			public void mouseDoubleClicked(MouseEvent e) {
				int index = list.getSelectedIndex();
				
				Rectangle bounds = list.getCellBounds(index, index);
				Point location = new Point(bounds.x, bounds.y);
				location = SwingUtilities.convertPoint(list, 
						location, 
						pluginAdapter.getSpringGlassPane());
				location.y -= 13;
				bounds.setLocation(location);
					 
				Image icon = ((Application)list.getSelectedValue())
						.icon.getImage();
				
				/* open report */
				if (index == 1) {
					ActionEvent event = new ActionEvent(StartPanel.this, 
							ActionEvent.ACTION_PERFORMED, 
							"open report");
					openReport.actionPerformed(event);
						
				/* new report */
				} else if (index == 0) {
					ActionEvent event = new ActionEvent(StartPanel.this, 
							ActionEvent.ACTION_PERFORMED, 
							"new report");
					newReport.actionPerformed(event);
				}
				
				pluginAdapter.getSpringGlassPane().showSpring(bounds, icon);
			}
		});
		
		
		setLayout(new GridBagLayout());
		
		JLabel chooseLabel = new JLabel(getLocalizedString("top"));
		chooseLabel.setFont(getFont());
		chooseLabel.setForeground(new Color(0x333333));
		
		JLabel doubleClickLabel = new JLabel(getLocalizedString("bottom"));
		doubleClickLabel.setFont(getFont());
		doubleClickLabel.setForeground(new Color(0x333333));
		
		GridBagConstraints constraints = new GridBagConstraints(0, 
				0, 
				1, 
				1, 
				1.0, 
				1.0,
				GridBagConstraints.SOUTH, 
				GridBagConstraints.NONE,
				new Insets(0, 0, 0, 0), 
				0, 
				0);
		add(chooseLabel, constraints);
		
		constraints = new GridBagConstraints(0, 
				1, 
				1, 
				1, 
				1.0, 
				1.0,
				GridBagConstraints.CENTER, 
				GridBagConstraints.NONE,
				new Insets(0, 0, 0, 0), 
				0, 
				0);
		add(list, constraints);
		
		constraints = new GridBagConstraints(0, 
				2, 
				1, 
				1, 
				1.0, 
				1.0,
				GridBagConstraints.NORTH, 
				GridBagConstraints.NONE,
				new Insets(0, 0, 0, 0), 
				0, 
				0);
		add(doubleClickLabel, constraints);
		
		/* file history */
		JPanel fileHistoryPanel = new JPanel();
		fileHistoryPanel.setOpaque(false);
		
		fileList = new JList();
		fileList.setFont(getFont());
		fileList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		fileList.setFocusable(false);
		fileList.setCursor(new Cursor(Cursor.HAND_CURSOR));
		fileList.setBackground(new Color(0xffffff));
		fileList.setBorder(BorderFactory.createMatteBorder(
						1, 1, 1, 1, new Color(0x828790)));
		fileList.setSelectionBackground(fileList.getBackground());
		fileList.setSelectionForeground(fileList.getForeground());
		DefaultAdvancedListCellRenderer renderer = new DefaultAdvancedListCellRenderer();
		renderer.setHighlightBackground(new Color(0x62b0f7));
		fileList.addMouseListener(renderer);
		fileList.addMouseMotionListener(renderer);
		fileList.setCellRenderer(renderer);
		fileList.addMouseListener(new MouseAdapter(){
			@Override
			public void mouseClicked(MouseEvent e) {
				if(e.getButton() == MouseEvent.BUTTON1) {
					if(fileList.getSelectedValue() == null) {
						return;
					}
					setHistoryFile((File)fileList.getSelectedValue());
					ActionEvent event = new ActionEvent(StartPanel.this, 
							ActionEvent.ACTION_PERFORMED, "open review file");
					openReportFile.actionPerformed(event);
				}
			}
		});
		

		JLabel fileHistoryLabel = new JLabel(getLocalizedString("history"));
		fileHistoryLabel.setFont(getFont().deriveFont(14.0f));

		GroupLayout layout = new GroupLayout(fileHistoryPanel);
		fileHistoryPanel.setLayout(layout);
		layout.setHorizontalGroup(
				layout.createSequentialGroup()
					.addGroup(layout.createParallelGroup()
						.addGroup(layout.createSequentialGroup()
							.addGap(10, 10, 10)
							.addComponent(fileList))
						.addGroup(layout.createSequentialGroup()
							.addContainerGap()
							.addComponent(fileHistoryLabel)))
					.addContainerGap()
		);
		layout.setVerticalGroup(
				layout.createSequentialGroup()
					.addContainerGap()
					.addComponent(fileHistoryLabel)
					.addPreferredGap(LayoutStyle.ComponentPlacement.RELATED)
					.addComponent(fileList)
		);
		
		constraints = new GridBagConstraints(0, 
				3, 
				1, 
				1, 
				1.0, 
				1.0,
				GridBagConstraints.NORTH, 
				GridBagConstraints.NONE,
				new Insets(0, 0, 0, 0), 
				0, 
				0);
		add(fileHistoryPanel, constraints);
	}
	
	private class FileHistoryChangeListener implements Serializable, 
			FileHistory.ChangeListener{
		private static final long serialVersionUID = -2354920467250368386L;
		@Override
		public void typeChanged(ChangeEvent ce) {
			Object source = ce.getSource();
			if(source instanceof FileHistory) {
				setFileHistory((FileHistory)source);
			}
		}
	}
	
	private void setFileHistory(FileHistory fileHistory) {
		setHistoryFiles(fileHistory.getFiles(ReviewerPlugin.FILE_HISTORY_TYPE));
	}
	
	private void setHistoryFiles(List<File> files) {
		Object selectedValue = fileList.getSelectedValue();
		
		DefaultListModel model = new DefaultListModel();
		
		for(File file: files) {
			model.addElement(file);
		}
		
		fileList.setModel(model);
		
		fileList.setSelectedValue(selectedValue, true);
	}
	
	private static class ApplicationListCellRenderer extends 
			DefaultListCellRenderer {
		private static final long serialVersionUID = -2427972393137841623L;
		public Component getListCellRendererComponent(JList list, Object value,
				int index, boolean isSelected, boolean cellHasFocus) {
			JLabel c;
			c = (JLabel) super.getListCellRendererComponent(list, value,
					index, isSelected, cellHasFocus);
			
			Application element = (Application) value;
			c.setBorder(BorderFactory.createEmptyBorder(32, 32, 32, 32));
			c.setFont(c.getFont().deriveFont(18.0f).deriveFont(Font.BOLD));
			c.setText(element.label);
			c.setIcon(element.icon);
			c.setHorizontalTextPosition(JLabel.CENTER);
			c.setVerticalTextPosition(JLabel.BOTTOM);
			if (isSelected) {
				c.setBackground(new Color(0xbfd72b));
				c.setForeground(new Color(0x666666));
			} else {
				c.setBackground(new Color(0x7f7f7f));
				c.setForeground(new Color(0xdddddd));
			}
			
			return c;
		}   
	}
	
	/**
	 * Returns an resource icon
	 * @param name name of icon
	 * @return
	 */
	private ImageIcon getRessourceIcon(String name) {
		return new ImageIcon(getClass().getResource("images/" + name));
	}
	private class Application implements Serializable {
		private static final long serialVersionUID = -4599827241701044078L;
		public ImageIcon icon;
		public String label;
		public Application(String label, String icon) {
			this.icon = getRessourceIcon(icon);
			this.label = label;
		}
	}
	
	protected void setHistoryFile(File historyFile) {
		this.historyFile = historyFile;
	}
	public File getHistoryFile() {
		return historyFile;
	}
	
	@Override
	public void setNextViewAction(Action action) {
	}
	
	@Override
	public void setPreviousViewAction(Action action) {
	}
	@Override
	public void applyReport() {
	}
	@Override
	public void setReport(Report report) {
	}
}
